<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片式图 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center :closable="false" show-icon></el-alert>
      <!-- step进度条 -->
      <el-steps align-center :space="200" :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-position="top"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- tab栏区域 -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="categoriesList"
        >
          <!-- 基本信息 -->
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <!-- 商品分类  options 数据源-->
            <el-form-item label="商品分类" prop>
              <el-cascader
                v-model="addForm.goods_cat"
                :options="goodsList"
                :props="goodsProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <!-- 商品参数 -->
            <el-form-item :key="item.attr_id" v-for="item in manyTableData" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  class="elcheckbox"
                  :checked="false"
                  :label="item"
                  border
                  :key="i"
                  v-for="(item,i) in item.attr_vals"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <!-- 商品属性 -->
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in onlyTableData">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <!-- 图片上传 -->
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="hearder"
              :on-success="handelSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 商品内容 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addIntroduce">添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片展示 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="30%">
      <img :src="previewPath" alt class="img" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        attrs: [],
        // 商品介 绍
        goods_introduce: '',
        // 上个
        oldActiveName:''
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格11', trigger: 'blur' },
           { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { min: 1, max: 100, message: '输入正确重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { min: 1, message: '数量至少为1', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 分类列表
      goodsList: [],
      goodsProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      //   根据id查询分类列表
      manyTableData: [],
      onlyTableData: [],
      //   图片上传
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      hearder: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '',
      dialogVisible: false
    }
  },
  methods: {
    //   //   商品分类数据列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('/categories')
      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('分类列表获取失败')
      this.goodsList = res.data
    },

    async categoriesList() {
      console.log(this.activeIndex)

      // 查询参数列表
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        console.log(res)
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
        console.log(this.manyTableData)

        console.log(this.manyTableData)
      } else if (this.activeIndex === '2') {
        alert(2)
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) return this.$http.error('获取商品属性失败')
        this.onlyTableData = res.data
        // console.log(this.onlyTableData)
      } else if (this.activeIndex === '4') {
           const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      }
    },
    // 获取参数列表
    handleChange() {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3)
        return (this.addForm.goods_cat = [])
    },
    // 监听 事件处理函数
    beforeTabLeave(activeName, oldActiveName) {
      //   console.log(activeName)
      //   console.log(this.addForm.goods_name.length)
      if (oldActiveName == 0 && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // 图片监听事件
    handlePreview(file) {
      console.log(file)
      this.previewPath = file.response.data.url
      this.dialogVisible = true
    },
    handleRemove(file) {
      // console.log(file)
      let filePath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    // 上传成功获取图片地址
    handelSuccess(response) {
      let pic = response.data.tmp_path
      this.addForm.pics.push(pic)
      console.log(this.addForm.pics)
    },
    async addIntroduce() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return this.$message.error('请填写完整表格')
      })
      // console.log(this.addForm);
      const form = _.cloneDeep(this.addForm)
      form.goods_cat = form.goods_cat.join(',')
      // console.log(form);
      // form.attrs.push(this.manyTableData)
      // console.log(this.manyTableData);
      // 处理动态参数
      this.manyTableData.forEach(item => {
        const obj = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(' ')
        }
        // item.attr_value = item.attr_value.join(' ')
        form.attrs.push(obj)
      })
      // 处理静态参数
      this.onlyTableData.forEach(item => {
        const obj = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        form.attrs.push(obj)
      })
      // console.log(form);

      const { data: res } = await this.$http.post('/goods', form)
      console.log(res)
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length !== 3) {
        return null
      } else {
        return this.addForm.goods_cat[2]
      }
    }
  },
  created() {
    //   商品分类数据列表
    this.getGoodsList()
  }
}
</script>
<style lang='css' scoped>
.img {
  width: 100%;
}
</style>